<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
class Performance extends Controller
{
    
    public function index()
    {
        $year = date('Y');
        $month = input()['month']?:date('m',time()-86400*5 );
        $startTime = strtotime($year.'-'.$month.'-01');
        $endTime = strtotime(date('Y-m-t',$startTime) )+86399;
        if(input()['page'] )
        {
            $adminId = session('uid','','admin');
            $list = db('performance')
                ->alias('p')
                ->field('p.*')
                ->join('admin a','a.id=p.admin_id')
                ->where('p.end_date','>=',$startTime)
                ->where('p.end_date','<=',$endTime);
            if(session('group_id','','admin') == 5)
            {
                $manager = db('admin')->field('name,id,group_members,group_name')->where('id',$adminId)->find();
                $groupMembers = $manager['group_members']?$manager['id'].','.$manager['group_members']:$manager['id'];
                $list = $list->where('p.admin_id','IN',$groupMembers );
            }
            else if(session('group_id','','admin') == 2)
            {
                $list = $list->where('p.admin_id',$adminId);
            }
            else if (session('group_id','','admin') != 1)
                return;
                
            if(session('uid','','admin') == 1)
            {
                //$list = $list->where('status','>',0);
            }
            $list = $list->order('a.department_id,p.admin_id ASC ,p.client_id ASC, p.id ASC')->select();
            foreach($list as $k=>$v)
            {
                $list[$k]['address'] = $v['province'] . $v['city'];
                $list[$k]['vote_date'] = date('m.d',$v['start_date']).'-'.date('m.d',$v['end_date']);
                $list[$k]['ratio'] = $v['client_ratio'].'/'.$v['salesman_radio'];
            }
            return ['code'=>0,'msg'=>'','count'=>500,'data'=>$list]; 
        }
        $this->assign([
            'month'=>$month,
            'year'=>$year,
        ]);
        return view();
    }
    
    /*public function settleList()
    {
        $settleStatus = isset(input()['settle_status'])?:1;
        if(input()['page'] )
        {
            $adminId = session('uid','','admin');
            $list = db('performance')
                ->alias('p')
                ->field('p.*')
                ->join('admin a','a.id=p.admin_id')
                ->where('p.status',1);
            $list = $list->order('a.department_id,p.admin_id ASC ,p.client_id ASC, p.id ASC')->select();
            foreach($list as $k=>$v)
            {
                $list[$k]['address'] = $v['province'] . $v['city'];
                $list[$k]['vote_date'] = date('m.d',$v['start_date']).'-'.date('m.d',$v['end_date']);
                $list[$k]['ratio'] = $v['client_ratio'].'/'.$v['salesman_radio'];
            }
            return ['code'=>0,'msg'=>'','count'=>500,'data'=>$list]; 
        }
        $this->assign([
            'settle_status'=>$settleStatus,
        ]);
        return view();
    }*/
    
    public function checkList()
    {
        $year = date('Y');
        $month = input()['month']?:date('m',time()-86400*5 );
        if(input()['page'] )
        {
            $adminId = session('uid','','admin');
            $list = db('performance')
                ->alias('p')
                ->field('p.*')
                ->join('admin a','a.id=p.admin_id')
                ->where('p.status',1);
            $list = $list->order('a.department_id,p.admin_id ASC ,p.client_id ASC, p.id ASC')->select();
            foreach($list as $k=>$v)
            {
                $list[$k]['address'] = $v['province'] . $v['city'];
                $list[$k]['vote_date'] = date('m.d',$v['start_date']).'-'.date('m.d',$v['end_date']);
                $list[$k]['ratio'] = $v['client_ratio'].'/'.$v['salesman_radio'];
            }
            return ['code'=>0,'msg'=>'','count'=>500,'data'=>$list]; 
        }
        $this->assign([
            'month'=>$month,
            'year'=>$year,
        ]);
        return view();
    }
    
    public function settleList()
    {
        $year = date('Y');
        $month = input()['month']?:date('m',time()-86400*5 );
        $startTime = strtotime($year.'-'.$month.'-01');
        $endTime = strtotime(date('Y-m-t',$startTime) )+86399;
        if(input()['page'] )
        {
            $adminId = session('uid','','admin');
            $list = db('performance')
                ->alias('p')
                ->field('p.*')
                ->join('admin a','a.id=p.admin_id')
                ->where('p.end_date','>=',$startTime)
                ->where('p.end_date','<=',$endTime)
                ->where('p.status','>',0);
            $list = $list->order('a.department_id,p.admin_id ASC ,p.client_id ASC, p.id ASC')->select();
            foreach($list as $k=>$v)
            {
                $list[$k]['address'] = $v['province'] . $v['city'];
                $list[$k]['vote_date'] = date('m.d',$v['start_date']).'-'.date('m.d',$v['end_date']);
                $list[$k]['ratio'] = $v['client_ratio'].'/'.$v['salesman_radio'];
            }
            return ['code'=>0,'msg'=>'','count'=>500,'data'=>$list]; 
        }
        $this->assign([
            'month'=>$month,
            'year'=>$year,
        ]);
        return view();
    }
    
    public function report()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];
            if(!$data['client_id'] || !$data['live_id'])
                return ['msg'=>'操作失败,未选择客户或直播间','icon'=>2];
            if(db('performance')->where('live_id',$data['live_id'])->value('id') != $data['id'])
                return ['msg'=>'操作失败,该直播已申报，请确认','icon'=>2];
            if(db('datatable_live_process')->where('live_id',$data['live_id'])->where('step','>',0)->value('step') && db('datatable_live_process')->where('live_id',$data['live_id'])->where('step','>',0)->value('step') < 4 && session('group_id','','admin') != 1)
                return ['msg'=>'操作失败,该直播未申请结算','icon'=>2];

            $data = $this->compute($data,0);
            if(!$data['id'])
            {
                $data['admin_id'] = session('uid','','admin');
                $data['admin_name'] = session('uname','','admin');
                $data['add_time'] = time();
            }
            $data['status'] = input('post.')['status'];
            $data['start_date'] = strtotime($data['start_date']);
            $data['end_date'] = strtotime($data['end_date']);
            if($data['id'])
            {
                unset($data['live_id']);
                $sqlStatus = db('performance')->where('id',$data['id']);
                if(session('uid','','admin') != 1)
                    $sqlStatus = $sqlStatus->where('admin_id',session('uid','','admin'));
                $sqlStatus = $sqlStatus->update($data);
                $sqlStatus = 1;
            }
            else
            {
                $sqlStatus = db('performance')->insert($data);
            }
            return $sqlStatus?['msg'=>'操作成功','icon'=>1,'code'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else
        {
            $id = input()['id'];
            if($id)
            {
                $data = db('performance')->where('id',$id)->find();
                $data['start_date'] = date('Y-m-d',$data['start_date']);
                $data['end_date'] = date('Y-m-d',$data['end_date']);
                $data['settle_date'] = $data['settle_date']=='0000-00-00'?'':$data['settle_date'];
                foreach ($data as $k=>$v)
                {
                    $data[$k] = str_replace("'",'',$data[$k]);
                    $data[$k] = str_replace(PHP_EOL,'　',$data[$k]);
                }
                //$data['title'] = str_replace("'",'',$data['title']);
                
                $giftFeeList = db('goods_orders')->alias('go')->field('g.*,go.count as goods_count,go.id as order_id')->join('goods g','g.id=go.goods_id')->where('go.live_id',$data['live_id'])->where('go.status','>=',0)->order('g.id ASC')->select();
                $liveFeeList = db('datatable_live_process')->where('live_id',$data['live_id'])->where('is_del',0)->order('activity_end_time ASC')->select();
                //db('datatable_live')->where('live_id',$data['live_id'])->where('is_del',0)->order('activity_end_time ASC')->select()?:
                
            }
            $clientList = db('client')->where('status',4);
            if(session('group_id','','admin') != 1 && session('group_id','','admin') != 8)
                $clientList = $clientList->where('xaid',session('uid','','admin'));
            $clientList = $clientList->order('qiandan_time DESC')->select();
            
            if(input('type') == 'settle')
            {
                if(is_numeric(trim($data['settle_remark'])))
                {
                    $data['otherSettle'] = db('performance')->field('client_final_income')->where('id','<>',$id)->where('settle_remark','LIKE',"%{$data['settle_remark']}%")->select();
                    $data['sumOtherSettle'] = db('performance')->where('settle_remark','LIKE',"%{$data['settle_remark']}%")->value('SUM(client_final_income)');
                    
                }
            }
            
            $this->assign([
                'clientList'=>$clientList,
                'data'=>$data,
                'giftFeeList'=>$giftFeeList,
                'liveFeeList'=>$liveFeeList,
            ]); 
            
            return input('type') == 'settle'?view('settle'):view(); 
        }
    }
    
    function saveField()
    {
        if(session('uid','','admin') == 1)
        {
            $id = input()['id'];
            if(input('field'))
            {
                $field = input()['field'];
                $value = input()['value'];
                $sqlStatus = db('performance')->where('id',$id)->update([ $field=>$value ]);
            }
            else if(input('post.'))
            {
                $data = input('post.');
                $sqlStatus = db('performance')->where('id',$id)->update($data);
            }
        }
        return ['msg'=>'操作成功','icon'=>1,'code'=>1];
    }
    
    function check()
    {
        if(session('uid','','admin') == 1)
        {
            $id = input()['id'];
            $sqlStatus = db('performance')->where('id','IN',$id)->update(['status'=>2,'check_time'=>time()]);
        }
        return $sqlStatus?['msg'=>'操作成功','icon'=>1,'code'=>1]:['msg'=>'操作失败','icon'=>2];
    }
    
    function compute($data=[],$type=0)
    {
        //$data = $type?json_decode($data,true):$data;
        $data = $type==1?input('post.'):$data;
        if($data['live_id'])
        {
            if(db('performance')->where('live_id',$data['live_id'])->value('id') != $data['id'])
                return ['msg'=>'操作失败,这场直播的业绩已经被录入过了','icon'=>1,'code'=>-1];
            if(db('datatable_live_process')->where('live_id',$data['live_id'])->where('step','>',0)->value('step') && db('datatable_live_process')->where('live_id',$data['live_id'])->where('step','>',0)->value('step') < 4 && session('group_id','','admin') != 1)
                return ['msg'=>'操作失败,该直播未申请结算','icon'=>2];
                
            foreach ($data as $k=>$v)
            {
                if($data[$k] == '')
                    ${$k} = 0;
                else
                    ${$k} = $data[$k];
            }
            if($data['live_id'])
                $data['total_income'] = $this->getTotalIncome($data['live_id'])['data']['total_income'];

            if($data['total_income'])
                $data['real_income'] = round( $data['total_income'] - $refund_income - $reduce_income - $live_fee - $plive_fee - $gift_fee - $travel_fee - $other_fee,2);
            if($data['real_income'] && $client_ratio != '')
                $data['client_income'] = round( $data['real_income'] * $client_ratio/100,2);
            if($data['client_income'] || $data['client_income'] == '0')
                $data['client_charges'] = round( $data['client_income'] * $client_sxfee_radio/100 ,2);
            if($data['client_income'] || $data['client_income'] == '0')
                $data['client_final_income'] = round( $data['client_income'] - $data['client_charges'] - $client_live_fee - $client_plive_fee - $client_gift_fee - $client_travel_fee - $client_other_fee + $client_other_income,2);
            if($data['real_income'] && ($data['salesman_radio']  || $data['salesman_radio'] == '0' ))
                $data['salesman_performance'] = round( $data['real_income'] * $data['salesman_radio']/100 + $reduce_income,2);
            if($data['salesman_performance'])
                $data['salesman_charges'] = round( $data['salesman_performance'] * 0.05,2);
            if($data['salesman_performance'])
                $data['salesman_final_performance'] = round( $data['salesman_performance'] - $data['salesman_charges'] - $salesman_recommend_fee - $salesman_live_fee - $salesman_plive_fee - $salesman_gift_fee - $salesman_travel_fee - $salesman_other_fee + $salesman_other_performance - $client_other_income,2);
            return $type==1? ['code'=>1,'data'=>$data]:$data;
        }
    }
    
    function getTotalIncome($live_id)
    {
        $voteSetting = Db::connect("live_db_config")->table('ims_wzbagent_vote_setting')->where('live_id',$live_id)->order('id DESC')->find();
        $data['start_date'] = date('Y-m-d',$voteSetting['start_at']);
        $data['end_date'] = date('Y-m-d',$voteSetting['end_at']);
        
        $data['total_income'] = Db::connect("live_db_config")->table('ims_wzbagent_giftlogs')->where('dateline','>=',$voteSetting['start_at'])->where('dateline','<=',$voteSetting['end_at']+300)->where('status',1)->where('live_id',$live_id)->sum('amount');
        $data['total_income'] = $data['total_income'] / 100;
        $data['title'] = Db::connect("live_db_config")->table('ims_wzbagent_lives')->where('id',$live_id)->value('title');
        $data['special_id'] = Db::connect("live_db_config")->table('ims_special_lives')->where('live_id',$live_id)->order('created_at DESC')->value('special_id');
        if($data['special_id'])
        {
            $data['special_pid'] = Db::connect("live_db_config")->table('ims_special')->where('special_id',$data['special_id'])->value('pid');
            $data['title'] = Db::connect("live_db_config")->table('ims_special')->where('special_id',$data['special_pid'])->value('special_name').'-'.$data['title'];
        }

        return ['code'=>1,'data'=>$data];
    }
    
    function summary()
    {
        $year = date('Y');
        $month = input()['month']?:date('m',time()-86400*5 );
        $startTime = strtotime($year.'-'.$month.'-01');
        $endTime = strtotime(date('Y-m-t',$startTime) )+86399;
        $departData = (session('group_id','','admin') == 1)?db('admin')->where('group_id',5)->where('status',1)->select():db('admin')->where('group_id',5)->where('status',1)->where('id',session('uid','','admin'))->select();
        foreach ($departData as $k=>$v)
        {
            $kkRows = [];
            $departData[$k]['group_members'] = $groupMembers = $v['group_members']?$v['id'].','.$v['group_members']:$v['id'];
            $departData[$k]['performance'] = $kRows[] = db('performance')->where('end_date','>=',$startTime)->where('end_date','<=',$endTime)->where('status','>=',1)->where('admin_id','IN',$groupMembers)->sum('salesman_final_performance');
            $departData[$k]['income'] = db('performance')->where('end_date','>=',$startTime)->where('end_date','<=',$endTime)->where('status','>=',1)->where('admin_id','IN',$groupMembers)->sum('total_income');
            $departData[$k]['count'] = db('performance')->where('end_date','>=',$startTime)->where('end_date','<=',$endTime)->where('status','>=',1)->where('admin_id','IN',$groupMembers)->count();
            $memberData = db('admin')->where('id','IN',$groupMembers)->where('join_time','<=',$endTime)->select();
            // foreach ($memberData as $kk=>$vv)
            // {
            //     $memberData[$kk]['performance'] = $kkRows[] = db('performance')->where('status',2)->where('admin_id',$vv['id'])->sum('salesman_final_performance');
            //     $memberData[$kk]['income'] = db('performance')->where('status',2)->where('admin_id',$vv['id'])->sum('total_income');
            //     $memberData[$kk]['count'] = db('performance')->where('status',2)->where('admin_id',$vv['id'])->count();
            // }
            // array_multisort($kkRows,SORT_DESC,SORT_NUMERIC,$memberData);
            $departData[$k]['member_data'] = $memberData;
        }
        array_multisort($kRows,SORT_DESC,SORT_NUMERIC,$departData);

        $memberData = db('admin')->where('group_id','IN','2,5')->where('join_time','<=',$endTime)->select();
        foreach ($memberData as $kk=>$vv)
        {
            $memberData[$kk]['performance'] = db('performance')->where('end_date','>=',$startTime)->where('end_date','<=',$endTime)->where('status','>=',1)->where('admin_id',$vv['id'])->sum('salesman_final_performance');
            $memberData[$kk]['income'] = db('performance')->where('end_date','>=',$startTime)->where('end_date','<=',$endTime)->where('status','>=',1)->where('admin_id',$vv['id'])->sum('total_income');
            $memberData[$kk]['count'] = db('performance')->where('end_date','>=',$startTime)->where('end_date','<=',$endTime)->where('status','>=',1)->where('admin_id',$vv['id'])->count();
            if($vv['status'] == 0 && $memberData[$kk]['performance'] == 0)
            {
                unset($memberData[$kk]);
            }
            else
                $kkRows[] = $memberData[$kk]['performance'];
        }
        array_multisort($kkRows,SORT_DESC,SORT_NUMERIC,$memberData);

        
        $this->assign([
            'month'=>$month,
            'year'=>$year,
            'departData'=>$departData,
            'memberData'=>$memberData,
        ]);
        return view(); 
    }
    
    
}